<script lang="jsx" setup>
import { inject, ref, watch } from 'vue';
import { Button as AButton, Button } from 'ant-design-vue';
import { SearchOutlined } from '@ant-design/icons-vue';
import { REQU, SignInInfoInvalidCondPair, useResp } from '@/net/requ.js';
import { getAssignedFileList } from '@/net/requ.js';
import router from '@/router';
import * as storage from '@/util/storage.js';
import { onBeforeRouteLeave } from 'vue-router';
import { filterUserIdEq } from '@/util';
const primaryMainElem = inject('primaryMainElem');
const tableCompo = ref();

const pkgList = ref([]);
const PkgListOf = filterUserIdEq(() => pkgList.value);

const RoutePath = R.prop(R.__, {
  '1': '/obj-detn',
  '11': '/obj-detn',
  '12': '/video-action',
  '21': '/seq-label',
  '23': '/text-classification',
});

// 进入标注界面前存储用户、包和题的 id
// 用于进入标注界面存取标注数据
// 也用于从标注界面回到此页初始化表格滚动到对应的行

/**
 * pkg, ques 
 * 题，取 packageId 及自身 id
 * 包，取 id
 * 负责人，取首个题包 id
 */
const PkgInfo = R.cond([
  [
    R.has('fileId'),
    record => ({
      pkg: record.packageId,
      ques: record.id,
    }),
  ],
  [
    R.has('taskPackageId'),
    record => ({
      pkg: record.id,
      ques: '',
    }),
  ],
  [
    R.has('userId'),
    record => ({
      pkg: R.compose( R.path([0, 'id']), PkgListOf, R.prop('userId') )(record),
      ques: '',
    }),
  ],
]);

onBeforeRouteLeave((to, from, next) => {
  const labelPathList = ['/obj-detn', '/video-action', '/seq-label', '/text-classification'];
  const isNotToLabel = () => R.compose( R.not, R.includes(to.path) )(labelPathList);
  isNotToLabel() && localStorage.removeItem('pkgInfo');
  next();
});

const taskId = inject('taskId');
const taskInfo = inject('taskInfo');
const loading = ref(false);

/** 此为审核状态，并非 `assignmentStatus` */
const statusWord = R.prop(R.__, { 1: '进行中', 2: '已完成' });

const OpBtn = record => operate => (
  <Button
    v-exist:task={operate}
    type="primary"
    ghost
    shape="round"
    size="small"
    onClick={() => {
      storage.write('operate', operate);
      storage.writeAsStr('pkgInfo', R.mergeRight({ user: record.userId }, PkgInfo(record)));
      router.push(RoutePath(taskInfo.value.type));
    }}>
    {{ default: () => operate }}
  </Button>
);

// 进入标注页面用 pkgInfo.pkg 请求到 fileList 存 localStorage
const OpBtnCol = ({ record }) => (
  <div class="op-btns">
    {R.map(OpBtn(record), ['标注', '查看', '审核'])}
  </div>
);

const userColumns = ref([
  {
    title: '序号',
    width: 70,
    customRender: ({ index }) => index + 1,
  },
  {
    title: '任务负责人',
    dataIndex: 'userId',
    customRender: ({ record }) => record.userName,
  },
  {
    title: '任务量',
    width: 80,
    dataIndex: 'fileNum',
  },
  {
    title: '任务状态',
    width: 90,
    dataIndex: 'status',
    customRender: ({ text }) => statusWord(text),
  },
  {
    title: '操作',
    width: 200,
    customRender: OpBtnCol,
  },
]);

const pkgFileMap = ref({});

const userList = ref([]);

const userExpandedRowKeys = ref([]);

const pkgColumns = ref([
  {
    title: '序号',
    width: 70,
    customRender: ({ index }) => index + 1,
  },
  {
    width: 150,
    title: '题包ID',
    dataIndex: 'id',
    customRender: ({ record }) => record.taskPackageId,
  },
  {
    title: '提交时间',
    width: 170,
    dataIndex: 'submitTime',
    customRender: ({ text }) => text || '--'
  },
  {
    title: '题包状态',
    dataIndex: 'packageStatus',
    customRender: ({ text }) => {
      const Color = R.prop(R.__, { 1: 'green', 2: 'rgb(200,0,0)' });
      const Txt = R.propOr('--', R.__, { 1: '已通过', 2: '未通过',  });
      return (<span style={{ color: Color(text) }}>{Txt(text)}</span>);
    },
  },
  {
    title: '操作',
    width: 200,
    customRender: OpBtnCol,
  },
]);

const pkgExpandedRowKeys = ref([]);

function onExpandPkg(expanded, record) {
  expanded && setFileList(record.id);
}

const fileColumns = ref([
  {
    title: '序号',
    width: 70,
    customRender: ({ index }) => index + 1,
  },
  // {
  //   ellipsis: true,
  //   width: 150,
  //   title: '题ID',
  //   dataIndex: 'fileId',
  // },
  {
    ellipsis: true,
    title: '文件名称',
    dataIndex: 'fileName',
  },
  {
    title: '提交时间',
    width: 170,
    dataIndex: 'submitTime',
    customRender: ({ text }) => text || '--'
  },
  {
    width: 90,
    ellipsis: true,
    title: '验收员',
    dataIndex: 'auditUserId',
    customRender: ({ record }) => record.auditUserName,
  },
  {
    title: '验收时间',
    width: 170,
    dataIndex: 'auditTime',
  },
  {
    ellipsis: true,
    width: 386,
    title: '驳回理由',
    dataIndex: 'remark',
    customRender: ({ text }) => text || '--',
  },
  {
    title: '题状态',
    dataIndex: 'auditStatus',
    width: 90,
    customRender: ({ text }) => {
      const Color = R.prop(R.__, { 1: 'green', 2: 'rgb(200,0,0)' });
      const Txt = R.propOr('待验收', R.__, { 1: '验收通过', 2: '验收驳回' });
      return (<span style={{ color: Color(text) }}>{Txt(text)}</span>);
    },
  },
  {
    title: '操作',
    width: 200,
    customRender: OpBtnCol,
  },
]);

const params = ref({
  taskId,
  tagUserName: '',
  status: '',
  start: 1,
  limit: 100,
  queryString: '',
  orderField: '',
  orderType: '',
});

watch(params, getPkgList, { deep: true });

async function initTableExpand() {
  const pkgInfo = storage.readAsObj('pkgInfo');
  if (!pkgInfo) { return; }

  userExpandedRowKeys.value = [pkgInfo.user];
  pkgExpandedRowKeys.value = [pkgInfo.pkg];
  await setFileList(pkgInfo.pkg);

  // id 对应数据的下标即表格行的下标，用表格行下标和单元格高度算 scrollTop
  const scrollTop = (cellHeight => {
    const propDic = {
      user: R.compose( R.findIndex(R.__, userList.value), R.propEq(R.__, 'userId') ),
      pkg: R.compose( R.findIndex(R.__, PkgListOf(pkgInfo.user)), R.propEq(R.__, 'id') ),
      ques: R.compose( R.findIndex(R.__, pkgFileMap.value[pkgInfo.pkg]), R.propEq(R.__, 'id') ),
    };

    return R.compose(
      R.transduce(
        R.compose(
          R.filter(R.gte(R.__, 0)),
          R.map(R.compose( R.add(cellHeight), R.multiply(cellHeight) )),
        ),
        R.add,
        0,
      ),
      R.values,
      R.mapObjIndexed((id, k) => R.call(propDic[k], id))
    )(pkgInfo);
  })(55);
  
  primaryMainElem.value.scroll({ top: scrollTop + tableCompo.value.$el.getBoundingClientRect().top });
}

function getPkgList() {
  loading.value = true;
  return REQU(`/api/task/assignedPackageList?${ new URLSearchParams(params.value) }`)
  .then(useResp({
    succ: result => {
      userList.value = R.map(R.omit(['assignmentPackageList']), result.data.list);
      pkgList.value = R.transduce(R.map(R.prop('assignmentPackageList')), R.concat, [], result.data.list);
      localStorage.setItem('pkgList', JSON.stringify(pkgList.value));

      initTableExpand();
    },
    fail: R.cond([SignInInfoInvalidCondPair()]),
  }))
  .finally(() => loading.value = false);
}

function setFileList(packageId) {
  if (pkgFileMap.value[packageId]?.length) { return; }

  loading.value = true;
  return getAssignedFileList(packageId)
  .then(useResp({
    succ: result => Reflect.set(pkgFileMap.value, packageId, result.data)
  }))
  .finally(() => loading.value = false);
}

const quesQuery = ref({
  params: { taskId, fileId: '',},
  list: [],
  userExpandedRowKeys: [],
  pkgExpandedRowKeys: [],
});

function getSpecifiedQues() {
  loading.value = false;
  return REQU(`/api/task/assignedFilePreciseQuery?${ new URLSearchParams(quesQuery.value.params) }`)
  .then(useResp({
    succ: result => {
      quesQuery.value.list = result.data;
      quesQuery.value.userExpandedRowKeys = [quesQuery.value.list[0].userId];
      quesQuery.value.pkgExpandedRowKeys = [quesQuery.value.list[0].assignmentPackageList[0].id]
    },
    fail: R.cond([
      SignInInfoInvalidCondPair(),
      [
        R.T,
        () => {
          quesQuery.value.list = [];
          quesQuery.value.userExpandedRowKeys = [];
          quesQuery.value.pkgExpandedRowKeys = [];
        }
      ],
    ]),
  }))
  .finally(() => (loading.value = false));
}

watch(
  () => quesQuery.value.params.fileId,
  value => value && getSpecifiedQues()
);

function main() {
  getPkgList();
}

main();
</script>

<template>
  <a-form layout="inline" :colon="false" style="display: flex; margin-bottom: 1em;">
    <a-form-item label="任务负责人">
      <a-input v-model:value="params.tagUserName" allow-clear placeholder="请输入姓名"></a-input>
    </a-form-item>

    <a-form-item label="任务状态" style="width: 150px;">
      <a-select v-model:value="params.status">
        <a-select-option value="">全部</a-select-option>
        <a-select-option :value="1">进行中</a-select-option>
        <a-select-option :value="2">已完成</a-select-option>
      </a-select>
    </a-form-item>

    <a-button
      @click="() => {
        params.tagUserName = '';
        params.status = '';
      }">
      重置
    </a-button>

    <a-input
      v-model:value="quesQuery.params.fileId"
      placeholder="输入题ID搜索"
      allow-clear
      style="width: 200px; margin-left: auto; margin-right: 1em; border-radius: 18px;">
      <template #prefix>
        <search-outlined style="color: rgb(181,181,181);" />
      </template>
    </a-input>
  </a-form>
  
  <a-config-provider :auto-insert-space-in-button="false">
    <template v-if="quesQuery.params.fileId">
      <a-table
        :loading="loading"
        :pagination="false"
        bordered
        row-key="userId"
        :columns="userColumns"
        :data-source="quesQuery.list"
        v-model:expandedRowKeys="quesQuery.userExpandedRowKeys"
        :scroll="{ x: 1360 }">
        <template #expandedRowRender="{ record }">
          <a-table
            :loading="loading"
            :pagination="false"
            bordered
            row-key="id"
            :columns="pkgColumns"
            :data-source="quesQuery.list[0].assignmentPackageList"
            v-model:expandedRowKeys="quesQuery.pkgExpandedRowKeys">
            <template #expandedRowRender="{ record }">
              <a-table
                :loading="loading"
                :pagination="false"
                bordered
                :row-key="row => `${ row.userId }-${ row.packageId }-${ row.id }`"
                :columns="fileColumns"
                :data-source="quesQuery.list[0].assignmentPackageList[0].packageFileEntityList">
              </a-table>
            </template>
          </a-table>
        </template>
      </a-table>
    </template>
    <template v-else>
      <a-table
        ref="tableCompo"
        :loading="loading"
        :pagination="false"
        bordered
        row-key="userId"
        :columns="userColumns"
        :data-source="userList"
        v-model:expandedRowKeys="userExpandedRowKeys"
        :scroll="{ x: 1360 }"
      >
        <template #expandedRowRender="{ record }">
          <a-table
            :loading="loading"
            :pagination="false"
            bordered
            row-key="id"
            :columns="pkgColumns"
            :data-source="PkgListOf(record.userId)"
            v-model:expandedRowKeys="pkgExpandedRowKeys"
            @expand="onExpandPkg">
            <template #expandedRowRender="{ record }">
              <a-table
                :loading="loading"
                :pagination="false"
                bordered
                :row-key="row => `${ row.userId }-${ row.packageId }-${ row.id }`"
                :columns="fileColumns"
                :data-source="pkgFileMap[record.id]">
              </a-table>
            </template>
          </a-table>
        </template>
      </a-table>
    </template>
  </a-config-provider>
</template>

<style>
.primary .task-list .op-btns {
  gap: .5em;
  justify-content: center;
}

.task-list .op-btns .ant-btn-round.ant-btn-sm {
  height: 22px;
  font-size: 12px;
}
</style>
